package com.compass.doctor.ui.home.fragment

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBFragment
import com.compass.doctor.callback.OnDialogBottomClick
import com.compass.doctor.databinding.FragmentHomeBinding
import com.compass.doctor.dialog.InquiryOrderDialog
import com.compass.doctor.callback.OnRefusalButtonClick
import com.compass.doctor.dialog.RefusalDialog
import com.compass.doctor.ui.MainViewModel
import com.compass.doctor.ui.WebDetailActivity
import com.compass.doctor.ui.consultation.ConsultationCenterActivity
import com.compass.doctor.ui.consultation.ConsultationDetailsActivity
import com.compass.doctor.ui.home.DoctorListActivity
import com.compass.doctor.ui.home.FollowUpActivity
import com.compass.doctor.ui.home.InquiryOrderActivity
import com.compass.doctor.ui.home.KnowledgeCenterActivity
import com.compass.doctor.ui.home.MedicalCareActivity
import com.compass.doctor.ui.home.MedicalCareOrderActivity
import com.compass.doctor.ui.home.TeamDoctorActivity
import com.compass.doctor.ui.home.VAServiceActivity
import com.compass.doctor.ui.home.adapter.ExigencyAdapter
import com.compass.doctor.ui.home.adapter.ExigencyMenuAdapter
import com.compass.doctor.ui.home.adapter.MenuAdapter
import com.compass.doctor.ui.home.view.InquiryInfoView
import com.compass.doctor.ui.home.viewmodel.HomeViewModel
import com.compass.doctor.ui.home.viewmodel.InquiryOrderViewModel
import com.compass.doctor.ui.message.NotificationActivity
import com.compass.doctor.ui.mine.CaSignatureActivity
import com.compass.doctor.ui.mine.EditUserDataActivity
import com.compass.doctor.ui.mine.view.DoctorInfoView
import com.compass.doctor.ui.patient.AddInquiryCaseHistory
import com.compass.doctor.ui.patient.PatientChatActivity
import com.compass.doctor.ui.patient.PractitionerToPatientChatActivity
import com.compass.doctor.ui.patient.WebRXExamineActivity
import com.compass.doctor.ui.patient.viewmodel.PatientViewModel
import com.compass.framework.constant.CLINICAL_RECEPTION
import com.compass.framework.constant.REFRESH_LAUNCH
import com.compass.framework.constant.REFRESH_MESSAGE
import com.compass.framework.constant.REFRESH_RX
import com.compass.framework.constant.REFRESH_RX_EXAMINE
import com.compass.framework.constant.REFUSE_RECEPTION
import com.compass.framework.constant.RX_DETAILS
import com.compass.framework.constant.TOOLS_URl
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.toJson
import com.compass.framework.ext.visible
import com.compass.framework.manager.DictionariesManager
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.Dictionaries
import com.compass.framework.model.InquiryMessage
import com.compass.framework.model.MenuItem
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.getStringFromResource
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.msg.MsgService
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
import com.netease.nimlib.sdk.msg.model.CustomNotification
import com.netease.nimlib.sdk.msg.model.CustomNotificationConfig
import com.netease.yunxin.kit.corekit.im.model.UserInfo
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import org.json.JSONObject


/**
 * Description： 首页Fragment
 * Date:2023/12/6 15:41
 */
class HomeFragment : BaseVBFragment<FragmentHomeBinding>(), OnRefreshListener {
    private val homeViewModel: HomeViewModel by viewModels()
    private val mainViewModel: MainViewModel by activityViewModels()
    private val inquiryOrderViewModel: InquiryOrderViewModel by viewModels()
    private var tags: String = ""
    private var tagsId: ArrayList<String> = ArrayList()//紧急代办tags
    private var dictionariesSort: ArrayList<Dictionaries> = ArrayList()//紧急代办分类
    private var menuItems: ArrayList<MenuItem> = ArrayList()
    private val patientViewModel: PatientViewModel by viewModels()
    private lateinit var customDoctorInfoView: DoctorInfoView //医生信息view
    private lateinit var inquiryInfoView: InquiryInfoView
    private lateinit var mMenuAdapter: MenuAdapter//功能菜单adapter
    private lateinit var exigencyMenuAdapter: ExigencyMenuAdapter //紧急代办tab adapter
    private lateinit var exigencyAdapter: ExigencyAdapter//紧急代办adapter
    private var patientId: String? = null//患者id
    private var orderId: String? = null//问诊编码

    override fun initView(view: View, savedInstanceState: Bundle?) {
        customDoctorInfoView = DoctorInfoView(requireContext(), 1)
        inquiryInfoView = InquiryInfoView(requireActivity())
        mMenuAdapter = MenuAdapter(1)
        exigencyMenuAdapter = ExigencyMenuAdapter()
        exigencyAdapter = ExigencyAdapter()
        when (UserInfoManager.getUserType()) {
            "1" -> {
                //医生
                initMenu()
                mBinding?.llMenu?.visible()
            }

            else -> {
                mBinding?.llMenu?.gone()
            }
        }


        mBinding?.apply {
            refreshLayout.setEnableRefresh(true)
            refreshLayout.setEnableLoadMore(false)
            refreshLayout.setOnRefreshListener(this@HomeFragment)
            flyContainer.addView(customDoctorInfoView)
            flyInquiryInfo.addView(inquiryInfoView)

            relNotification.onClick {
                //通知
                NotificationActivity.start(requireContext())
            }

            rcyMenu.apply {
                layoutManager =
                    LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
                adapter = mMenuAdapter
                indicator.setWithRecyclerView(rcyMenu, LinearLayoutManager.HORIZONTAL)
            }


            mMenuAdapter.onItemClickListener = { view: View, position: Int ->
                onMenuClick(menuItems[position].id)
            }


            rcyExigencyMenu.apply {
                layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
                adapter = exigencyMenuAdapter
            }

            exigencyMenuAdapter.onItemClickListener = { view: View, position: Int ->
//                menuItems[position].isSelect = !menuItems[position].isSelect
                dictionariesSort[position].isSelect = !dictionariesSort[position].isSelect
                tagsId.clear()

                for (tagItem in dictionariesSort) {
                    if (tagItem.isSelect) tagsId.add(tagItem.value)
                }

                exigencyMenuAdapter.notifyDataSetChanged()
                tags = tagsId.toString()
                getUrgency()
            }

            rcyInformation.apply {
                layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
                adapter = exigencyAdapter
            }
            exigencyAdapter.onItemClickListener = { view: View, position: Int ->
                val item = exigencyAdapter.getItem(position)
                if (item != null) {
                    when (item.type) {
                        6 -> {
                            //需方审核待办
                            WebRXExamineActivity.start(
                                context = requireActivity(),
                                url = RX_DETAILS + item.businessId,
                                title = "处方详情",
                                id = item.businessId, 1
                            )
                        }

                        5 -> {
                            //问诊结束待办
                            patientId = item.message.patientId
                            orderId = item.businessId
                            patientId?.let {
                                //查询当前患者是否有病历
                                patientViewModel.getInquiryCaseHistory(it)
                            }

                        }

                        4 -> {//医护上门待办
                            MedicalCareOrderActivity.start(requireContext(), item.businessId)
                        }

                        3 -> {//会诊接诊待办
                            ConsultationDetailsActivity.start(requireContext(), item.businessId, 2)
                        }

                        2 -> { //处方审核

                            WebRXExamineActivity.start(
                                context = requireActivity(),
                                url = RX_DETAILS + item.businessId,
                                title = "处方详情",
                                id = item.businessId, 0
                            )

                        }

                        1 -> {
                            //接诊待办
                            InquiryOrderDialog.Builder(
                                requireActivity(),
                                item.businessId,
                                onDialogBottomClick
                            ).show()

                        }
                    }
                }
            }
        }
    }

    private var inquiry: InquiryMessage? = null
    private var onRefusalBottomClick = object : OnRefusalButtonClick {
        override fun onButtonCallBack(orderId: String, msg: String) {
            showLoading()
            inquiryOrderViewModel.clinicalReception(orderId, 2, msg)

        }

    }

    private var onDialogBottomClick = object : OnDialogBottomClick {
        override fun onDialogButtonCallBack(inquiryMessage: InquiryMessage, msgType: String) {
            inquiry = inquiryMessage
            when (msgType) {
                "Refusal" -> {
                    //拒诊
                    RefusalDialog.Builder(
                        requireActivity(),
                        inquiryMessage.orderId,
                        onRefusalBottomClick
                    ).show()
                }

                "Treatment" -> {
                    //转诊
                    DoctorListActivity.start(requireContext(), 2, inquiryMessage.orderId)
                }

                "Reception" -> {
                    //接诊操作
                    if (UserInfoManager.isCASignature()) {
                        showLoading()
                        inquiryOrderViewModel.clinicalReception(inquiryMessage.orderId, 1)
                    } else {
                        CaSignatureActivity.start(requireContext())
                    }

                }

            }
        }
    }


    override fun initData() {
        showLoading()

        mainViewModel.getAllDictionaries()
//        if (DictionariesManager.getDoctorUrgencyBacklogType().isNullOrEmpty()) {
//            mainViewModel.getAllDictionaries()
//        } else {
//            mainViewModel.dictionariesLiveData.value =
//                DictionariesManager.getDoctorUrgencyBacklogType()
//                    ?.toBeanOrNull<MutableList<Dictionaries>>()
//        }

        mainViewModel.allDictionariesLiveData.observe(this) {
            //doctor_urgency_backlog_type
            it?.let {
                when (UserInfoManager.getUserType()) {
                    "1" -> {
                        mainViewModel.dictionariesLiveData.value =
                            it.doctor_urgency_backlog_doctor_type
                        DictionariesManager.saveDoctorUrgencyBacklogType(it.doctor_urgency_backlog_doctor_type.toJson())
                    }

                    "2" -> {
                        mainViewModel.dictionariesLiveData.value =
                            it.doctor_urgency_backlog_nurse_type
                        DictionariesManager.saveDoctorUrgencyBacklogType(it.doctor_urgency_backlog_nurse_type.toJson())
                    }

                    "3" -> {
                        mainViewModel.dictionariesLiveData.value =
                            it.doctor_urgency_backlog_pharmacist_type
                        DictionariesManager.saveDoctorUrgencyBacklogType(it.doctor_urgency_backlog_pharmacist_type.toJson())
                    }
                }

                //后期优化
                DictionariesManager.savePrescriptionFrequency(it.prescription_frequency.toJson())
                DictionariesManager.savePrescriptionChannel(it.prescription_channel.toJson())
                DictionariesManager.savePrescriptionUsage(it.prescription_usage.toJson())
                DictionariesManager.saveNurseProjectType(it.nurse_project_type.toJson())
                DictionariesManager.saveNurseStatus(it.app_order_nurse_status.toJson())
                DictionariesManager.saveConsultationStatus(it.medical_consultation_status.toJson())
                DictionariesManager.saveConsultationStatus(it.medical_consultation_status.toJson())
                DictionariesManager.saveParticipationStatus(it.medical_consultation_doctor_status.toJson())
                DictionariesManager.saveOrderStatus(it.order_prescription_status.toJson())
                DictionariesManager.saveOrderConsultationType(it.order_consultation_type.toJson())
                DictionariesManager.saveWalletLogType(it.doctor_wallet_log_type.toJson())
                DictionariesManager.saveWalletLogSource(it.doctor_wallet_log_source.toJson())
                DictionariesManager.saveOrderInspectionSource(it.order_inspection_status.toJson())
                DictionariesManager.saveNotificationType(it.doctor_notification_message_type.toJson())
                DictionariesManager.saveDoctorPosition(it.doctor_position.toJson())
                DictionariesManager.saveInspectionReportType(it.inspection_report_type.toJson())
                DictionariesManager.saveAfterStatus(it.order_nurse_after_sale_apply_status.toJson())
            }

        }
        mainViewModel.userLiveData.observe(this) {
            it?.let { doctorInfo ->
                mBinding?.tvHospitalName?.text = doctorInfo.getHospitalNameString()
                customDoctorInfoView.setDoctorInfo(doctorInfo)
//                LogUtil.d("医生信息：${doctorInfo.toJson()}")
                if (doctorInfo.name.isEmpty() || (doctorInfo.auditStatus == -1 || doctorInfo.auditStatus == 0)) {
                    EditUserDataActivity.start(requireContext(),doctorInfo.auditStatus,doctorInfo.auditReason)
                }
            }


        }

        mainViewModel.dictionariesLiveData.observe(this) {
            it?.let {
                dictionariesSort = it as ArrayList<Dictionaries>
                exigencyMenuAdapter.setData(dictionariesSort)
            }

        }
        homeViewModel.doctorUrgencyLiveData.observe(this) {
            exigencyAdapter.clear()
            it?.let { list ->
                if (list.isEmpty()) {
                    mBinding?.emptyView?.visible()
                    mBinding?.emptyView?.setText("暂无待办")
                } else {
                    exigencyAdapter.setData(it)
                    mBinding?.emptyView?.gone()
                }
            } ?: kotlin.run {
                mBinding?.emptyView?.visible()
                mBinding?.emptyView?.setText("暂无待办")
            }

            dismissLoading()
        }
        mainViewModel.todayNumberLiveData.observe(this) {
            it?.let { todayNumber ->
                if (todayNumber.unreadMsgNum > 0) mBinding?.imgMessage?.visible() else mBinding?.imgMessage?.gone()
                inquiryInfoView.setInquiryInfo(todayNumber)
                if (todayNumber.nurseWaitExecutionNum > 0 && !UserInfoManager.getUserType()
                        .equals("3")
                ) {
                    mBinding?.llCallPolice?.visible()
                } else {
                    mBinding?.llCallPolice?.gone()
                }

            }
        }
        //拒诊
        inquiryOrderViewModel.turnDownLiveData.observe(this) {
            dismissLoading()
            getUrgency()
        }
        //接诊操作
        inquiryOrderViewModel.receptionLiveData.observe(this) {
            dismissLoading()
            if (it) {
                LiveDataBus.get().with(CLINICAL_RECEPTION).postValue(CLINICAL_RECEPTION)
                inquiry?.let { details ->
                    if (details.consultationType == 1) {
                        if (UserInfoManager.getUserType() == "1") {
                            PatientChatActivity.start(
                                requireContext(),
                                UserInfo(
                                    details.patientWyyxAccId,
                                    details.patientName,
                                    details.patientAvatar
                                ),
                                details.patientId
                            )
                        } else {
                            PractitionerToPatientChatActivity.start(
                                requireContext(),
                                UserInfo(
                                    details.patientWyyxAccId,
                                    details.patientName,
                                    details.patientAvatar
                                ),
                                details.patientId
                            )
                        }


                    } else {
                        InquiryOrderActivity.start(requireContext(), 1)
                    }
                }
            }
        }
        patientViewModel.inquiryCaseLiveData.observe(this) { case ->
            dismissLoading()
            case?.let {
                AddInquiryCaseHistory.start(
                    requireContext(),
                    patientId,
                    case.diseaseDescription,
                    it.id,
                    orderId, 2
                )
            }
        }


        //这里的通知后续根据通知消息后面再重新优化
        LiveDataBus.get().with(REFRESH_RX, String::class.java).observe(this) {
            //处方审核操作通知  护师操作刷新
            getUrgency()
        }

        //药师审核刷新
        LiveDataBus.get().with(REFRESH_RX_EXAMINE, String::class.java).observe(this) {
            //处方审核操作通知  护师操作刷新
            getUrgency()
        }

        LiveDataBus.get().with(REFRESH_LAUNCH, String::class.java).observe(this) {
            //会诊加入拒绝
            homeViewModel.getDoctorUrgency(tags)
        }


        LiveDataBus.get().with(REFRESH_MESSAGE, String::class.java)
            .observe(this) {
                getUrgency()
            }

        LiveDataBus.get().with(REFUSE_RECEPTION, String::class.java)
            .observe(this) {
                //拒诊 转诊
                getUrgency()
            }
        LiveDataBus.get().with(CLINICAL_RECEPTION, String::class.java)
            .observe(this) {
                // 接诊 结束
                getUrgency()
            }

        getUrgency()//获取紧急代办
    }

    override fun intListener() {

        mBinding?.llCallPolice?.onClick {
            val intent = Intent()
            intent.action = Intent.ACTION_DIAL
            intent.data =
                Uri.parse("tel:${UserInfoManager.getUserInfo()?.appHospitalConfigRespVO?.alarmCall}")
            startActivity(intent)
        }
    }

    private fun initMenu() {
        menuItems.add(
            MenuItem(
                1,
                1,
                getStringFromResource(R.string.menu_medical_care),

                R.mipmap.icon_yh
            )
        )
        menuItems.add(
            MenuItem(
                1,
                2,
                getStringFromResource(R.string.chronic_disease_follow_up),
                R.mipmap.icon_chronic_disease_follow_up
            )
        )
        menuItems.add(
            MenuItem(
                1,
                3,
                getStringFromResource(R.string.knowledge_center),
                R.mipmap.icon_knowledge_center
            )
        )
        menuItems.add(
            MenuItem(
                1,
                4,
                getStringFromResource(R.string.consultation_center),
                R.mipmap.icon_added_service
            )
        )
        menuItems.add(
            MenuItem(
                1,
                5,
                getStringFromResource(R.string.menu_common_tools),
                R.mipmap.icon_team_doctors
            )
        )
        menuItems.add(
            MenuItem(
                1,
                6,
                getStringFromResource(R.string.menu_team_doctors),
                R.mipmap.icon_common_tools
            )
        )
        mMenuAdapter.setData(menuItems)

    }

    /**
     * 首页菜单点击事件
     */
    private fun onMenuClick(id: Int) {
        when (id) {
            1 -> {

                //增值服务
                VAServiceActivity.start(requireContext())
            }

            2 -> {
                //随访中心
                FollowUpActivity.start(requireContext())
            }

            3 -> {
                //知识中心
                KnowledgeCenterActivity.start(requireContext())
            }

            4 -> {
//                if (UserInfoManager.isExamine()) {
//                    //会诊中心
//                    ConsultationCenterActivity.start(requireContext())
//                } else {
//                    showToast("您的资料还在审核中")
//                }
                ConsultationCenterActivity.start(requireContext())
            }

            5 -> {
                //团队医生
                TeamDoctorActivity.start(requireContext())
            }

            6 -> {
                //常用工具
                WebDetailActivity.start(requireContext(), TOOLS_URl, "常用工具")
//                sendPostDiagnosisMessage("这是诊后建议内容","1255","1703146629544")


//                 构造自定义通知，指定接收者
//                val notification = CustomNotification()
//                notification.sessionId = "1803679279905755598"
//                notification.sessionType = SessionTypeEnum.P2P
//
//                // 构建通知的具体内容。为了可扩展性，这里采用 json 格式，以 "id" 作为类型区分。
//                val json = JSONObject()
//                json.put("id", "2")
//                val data = JSONObject()
//                data.put("body", "发送消息")
//                data.put(
//                    "url",
//                    "https://img2.baidu.com/it/u=1814561676,2470063876&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500"
//                )
//                json.put("data", data)
//                notification.content = json.toString()
//                // 若接收者不在线，则当其再次上线时，将收到该自定义系统通知。若设置为 true，则再次上线时，将收不到该通知。
//                notification.isSendToOnlineUserOnly = true
//                // 配置 CustomNotificationConfig
//                val config = CustomNotificationConfig()
//                // 需要推送
//                config.enablePush = true
//                config.enableUnreadCount = true
//                notification.config = config
//                // 设置的推送文案
//                notification.apnsText = "设置的推送文案"
//
//                // 自定义推送属性
//                val pushPayload = HashMap<String, Any>()
//                pushPayload["key1"] = "payload 1"
//                pushPayload["key2"] = 2015
//                notification.pushPayload = pushPayload
//                NIMClient.getService(MsgService::class.java).sendCustomNotification(notification)
//                showToast("发送测试系统通知")

            }

        }

    }

    private fun getUrgency() {
        if (tags.isNotEmpty() && tags.length > 1) {
            tags = tags.substring(1, tags.length - 1)
        }
        homeViewModel.getDoctorUrgency(tags)
        mainViewModel.orderTodayCount()
        mainViewModel.getUserInfo()
    }


    override fun onRefresh(refreshLayout: RefreshLayout) {
        getUrgency()
        //首页刷新业务
        refreshLayout.finishRefresh()
    }


}